package com.hs.jhzd.config.mq;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

import com.hs.jhzd.config.MqCondition;

@Configuration
@EnableRabbit
@Conditional(MqCondition.class)
public class RabbitmqConfiguration {
  /** The props. */
  @Autowired
  private RabbitProperties props;

  /**
   * rabbitListenerContainerFactory.
   * 
   * @return rabbitListenerContainerFactory
   */
  @Bean
  public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(defaultConnectionFactory());
    factory.setMaxConcurrentConsumers(5);
    factory.setMessageConverter(new Jackson2JsonMessageConverter());
    return factory;
  }

  /**
   * 默认连接工厂.
   *
   * @return ConnectionFactory
   */
  @Bean
  public ConnectionFactory defaultConnectionFactory() {
    CachingConnectionFactory cf = new CachingConnectionFactory();
    cf.setAddresses(this.props.getAddresses());
    cf.setUsername(this.props.getUsername());
    cf.setPassword(this.props.getPassword());
    cf.setVirtualHost(this.props.getVirtualHost());
    return cf;
  }

  /**
   * Amqp admin.
   *
   * @return the amqp admin
   */
  @Bean
  public AmqpAdmin amqpAdmin() {
    return new RabbitAdmin(defaultConnectionFactory());
  }
}
